package com.zk.qqrobot.util;

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class RestUtil {
    private static RestTemplate restTemplate = new RestTemplate();

    public static String forGet(String url){
        List<MediaType> acceptableMediaTypes = new ArrayList<>();
        acceptableMediaTypes.add(MediaType.ALL);
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.TEXT_HTML);
        header.setAccept(acceptableMediaTypes);
        header.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, header);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        return exchange.getBody();
    }

    public static String forPost(String url,Map<String,Object> param){
        MultiValueMap<String, Object> map= new LinkedMultiValueMap<String, Object>();
        Set<String> strings = param.keySet();
        for (String key:strings){
            map.add(key,param.get(key));
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
        return restTemplate.postForEntity(url, request,String.class).getBody();
    }
}
